package dper.study.codes.concurrent.utils;



import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import java.text.SimpleDateFormat;

/**
 * Created by leichen on 2017/3/21.
 */
public class ThreadSafeSimpleDateFormatUtil {

    private final static String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    private final static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() ;

    private static ThreadLocal<Integer> threadLocal_int = new ThreadLocal<Integer>(){
        public Integer initialValue(){
            return 0 ;
        }
    } ;

    public static Integer getThreadLocalInt(){
        return threadLocal_int.get() ;
    }

    public static void setThreadLocalInt(int i){
        threadLocal_int.set(i);
    }

    public static DateFormat getDateFormat(){
        DateFormat df = (DateFormat)threadLocal.get() ;
        System.out.println(Thread.currentThread() + " getDateFormat "+df ) ;
        if(df==null){
            df = new SimpleDateFormat(DATE_FORMAT) ;
            System.out.println(Thread.currentThread() + " new  SimpleDateFormat "+df ) ;
            threadLocal.set(df);
        }
        return  df ;
    }
    public static Date parse(String textDate) throws ParseException {
        return getDateFormat().parse(textDate);
    }

    public static void main(String[] argv){
        try {
            Date d = ThreadSafeSimpleDateFormatUtil.parse("2017-03-21 18:19:07") ;
            System.out.println(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
